#include <mysql.h>
#include <iostream>

using namespace std;


void create_students(MYSQL * mysql)
{
    string sql = "insert into student (name,del) value (?,?)";
    
    MYSQL_STMT* stmt = mysql_stmt_init(mysql);
    
    mysql_stmt_prepare(stmt,sql.c_str(),sql.length());

    MYSQL_BIND bind[2];

    unsigned long lens[2];
    
    bind[0].buffer_type = MYSQL_TYPE_VARCHAR;
    bind[1].buffer_type = MYSQL_TYPE_LONG;

    int num = 2;
    char name[] = "black";
    int del = 0;

    bind[0].buffer_length = sizeof(char) * strlen(name);
    bind[1].buffer_length = sizeof(int);

    bind[0].buffer = name;
    bind[1].buffer = &del;

    lens[0] = strlen(name);

    bind[0].length =  &lens[0];
    bind[1].length = NULL;

    bind[0].is_null = 0;
    bind[1].is_null = 0;

    bind[0].is_unsigned = false;
    bind[1].is_unsigned = false;

    mysql_stmt_bind_param(stmt,bind);

    for (unsigned i = 0; i < 0xffffff; i++)
    {
        // cout << "stmt error : " << mysql_stmt_errno(stmt) << endl;
    // cout << "mysql error : " << mysql_errno(mysql) << endl;

    mysql_stmt_execute(stmt);

    // cout << "stmt error : " << mysql_stmt_errno(stmt) << endl;
    // cout << "stmt error : " << mysql_stmt_error(stmt) << endl;
    // cout << "mysql error : " << mysql_errno(mysql) << endl;

    int affect_row_count = mysql_stmt_affected_rows(stmt);

    // cout << "affect row count" << affect_row_count << endl;
    }

    
    

    mysql_stmt_close(stmt);

    // cout << "create end" << endl;
}

int main(){
    cout << "start" << endl;
    MYSQL mysql;
    mysql_init(&mysql);
    if(!mysql_real_connect(&mysql,"localhost","root","123456","school",0,NULL,0))
    {
        cout << "connect fail"  << mysql_error(&mysql) << endl;
        return 1;
    }
 
    if(mysql_query(&mysql,"show tables"))
    {
        cout << mysql_error(&mysql) << endl;
        mysql_close(&mysql);
        cout << "error" << endl;
        return 2;
    }
    
    MYSQL_RES * res = mysql_store_result(&mysql);

    if(mysql_errno(&mysql))
    {
        cout << "error to store result" << endl;
        return 3;
    }

    cout << "total :" << res->row_count << endl;

    MYSQL_ROW row;
    unsigned int num_fields;
    unsigned int i;

    num_fields = mysql_num_fields(res);
    while ((row = mysql_fetch_row(res)))
    {
    unsigned long *lengths;
    lengths = mysql_fetch_lengths(res);
    for(i = 0; i < num_fields; i++)
    {
        printf("[%.*s] ", (int) lengths[i],
                row[i] ? row[i] : "NULL");
    }
    printf("\n");
    }


    
   create_students(&mysql);

    mysql_close(&mysql);
    return 0;
}